package com.klm.easymq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.klm.easymq.entity.Message;
import com.klm.easymq.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Easy-MQ 消息控制器
 * @author klm
 */
@RestController
@RequestMapping("/easymq/message")
public class EasyMqMessageController {

    @Autowired
    private MessageService messageService;

    /**
     * 保存消息
     */
    @PostMapping("/save")
    public Map<String, Object> saveMessage(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        try {
            message.setCreateTime(LocalDateTime.now());
            boolean success = messageService.save(message);
            result.put("success", success);
            result.put("message", success ? "消息保存成功" : "消息保存失败");
            result.put("data", message);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息保存异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据traceId查询消息
     */
    @GetMapping("/{traceId}")
    public Map<String, Object> getMessage(@PathVariable String traceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Message message = messageService.getById(traceId);
            result.put("success", true);
            result.put("data", message);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询消息异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询消息
     */
    @GetMapping("/page")
    public Map<String, Object> getMessagePage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String topic,
            @RequestParam(required = false) String status) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Message> page = new Page<>(current, size);
            QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
            
            if (topic != null && !topic.isEmpty()) {
                queryWrapper.like("topic", topic);
            }
            if (status != null && !status.isEmpty()) {
                queryWrapper.eq("status", status);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<Message> messagePage = messageService.page(page, queryWrapper);
            result.put("success", true);
            result.put("data", messagePage);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "分页查询异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 更新消息
     */
    @PutMapping("/update")
    public Map<String, Object> updateMessage(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = messageService.updateById(message);
            result.put("success", success);
            result.put("message", success ? "消息更新成功" : "消息更新失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息更新异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{traceId}")
    public Map<String, Object> deleteMessage(@PathVariable String traceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = messageService.removeById(traceId);
            result.put("success", success);
            result.put("message", success ? "消息删除成功" : "消息删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "消息删除异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取消息统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getMessageStats() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = messageService.count();
            long successCount = messageService.count(new QueryWrapper<Message>().eq("status", "SUCCESS"));
            long errorCount = messageService.count(new QueryWrapper<Message>().eq("status", "ERROR"));
            
            result.put("success", true);
            result.put("data", Map.of(
                "totalCount", totalCount,
                "successCount", successCount,
                "errorCount", errorCount,
                "successRate", totalCount > 0 ? (double) successCount / totalCount : 0
            ));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计信息异常: " + e.getMessage());
        }
        return result;
    }
} 